package com.haohan.cloud.scm.manage.core.impl;

import cn.hutool.core.util.StrUtil;
import com.haohan.cloud.scm.api.constant.ScmCacheNameConstant;
import com.haohan.cloud.scm.api.constant.enums.manage.PhotoTypeEnum;
import com.haohan.cloud.scm.api.manage.dto.PhotoGroupDTO;
import com.haohan.cloud.scm.api.manage.dto.ShopExtDTO;
import com.haohan.cloud.scm.api.manage.entity.Merchant;
import com.haohan.cloud.scm.api.manage.entity.PhotoGroupManage;
import com.haohan.cloud.scm.api.manage.entity.Shop;
import com.haohan.cloud.scm.api.manage.req.shop.ShopEditReq;
import com.haohan.cloud.scm.api.manage.vo.MerchantShopVO;
import com.haohan.cloud.scm.api.manage.vo.PhotoVO;
import com.haohan.cloud.scm.api.manage.vo.ShopVO;
import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import com.haohan.cloud.scm.common.tools.thread.ScmGlobalThreadPool;
import com.haohan.cloud.scm.goods.core.GoodsCoreService;
import com.haohan.cloud.scm.manage.core.PhotoManageCoreService;
import com.haohan.cloud.scm.manage.core.ShopManageCoreService;
import com.haohan.cloud.scm.manage.service.MerchantService;
import com.haohan.cloud.scm.manage.service.ShopService;
import com.haohan.cloud.scm.manage.utils.ScmManageUtils;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author dy
 * @date 2019/9/12
 */
@Service
@AllArgsConstructor
public class ShopManageCoreServiceImpl implements ShopManageCoreService {

    private final ShopService shopService;
    private final PhotoManageCoreService photoManageCoreService;
    private final MerchantService merchantService;
    private final ScmManageUtils scmManageUtils;
    private final GoodsCoreService goodsCoreService;

    /**
     * 获取店铺详情 带图片
     *
     * @param id
     * @return
     */
    @Override
    public ShopExtDTO fetchShopInfo(String id) {
        Shop shop = shopService.getById(id);
        if (null == shop) {
            throw new ErrorDataException("店铺有误");
        }
        ShopExtDTO shopDTO = new ShopExtDTO(shop);
        Merchant merchant = merchantService.getById(shop.getMerchantId());
        if (null != merchant) {
            shopDTO.setMerchantName(merchant.getMerchantName());
        }
        // 轮播图
        shopDTO.setPhotoList(fetchPhotoList(shopDTO.getPhotoGroupNum()));
        // 店铺收款码
        shopDTO.setPayCodeList(fetchPhotoList(shopDTO.getPayCode()));
        // 店铺二维码
        shopDTO.setQrcodeList(fetchPhotoList(shopDTO.getQrcode()));
        // 店铺Logo
        shopDTO.setShopLogoList(fetchPhotoList(shopDTO.getShopLogo()));
        return shopDTO;
    }

    /**
     * 获取图片组图片列表
     *
     * @param groupNum
     * @return
     */
    private List<PhotoVO> fetchPhotoList(String groupNum) {
        List<PhotoVO> photoList;
        if (StrUtil.isNotBlank(groupNum)) {
            PhotoGroupDTO groupDTO = photoManageCoreService.fetchByGroupNum(groupNum);
            if (null != groupDTO) {
                return groupDTO.getPhotoList().stream().map(PhotoVO::new).collect(Collectors.toList());
            }
        }
        photoList = new ArrayList<>();
        return photoList;
    }

    /**
     * 获取平台商家的采购配送店铺
     * (目前在采购单商品导入时使用)
     *
     * @param pmId 可不传
     * @return 失败为null
     */
    @Override
    public ShopExtDTO fetchPurchaseShop(String pmId) {
        // 平台商家
        Merchant merchant = merchantService.fetchPlatformMerchant();
        if (null == merchant) {
            return null;
        } else if (StrUtil.isNotBlank(pmId) && !StrUtil.equals(pmId, merchant.getId())) {
            // pmId 和平台商家不匹配
            return null;
        }
        Shop shop = shopService.fetchPdsShop(merchant.getId());
        if (null == shop) {
            return null;
        }
        ShopExtDTO shopExt = new ShopExtDTO(shop);
        shopExt.setMerchantName(merchant.getMerchantName());
        return shopExt;
    }

    /**
     * 获取商家店铺
     *
     * @param merchantId
     * @return 店铺列表可能为空
     */
    @Override
    @Cacheable(value = ScmCacheNameConstant.MANAGE_MERCHANT_SHOP, key = "#merchantId", condition = "#merchantId != null")
    public MerchantShopVO fetchMerchantShop(String merchantId) {
        // 平台商家
        Merchant merchant = merchantService.getById(merchantId);
        if (null == merchant) {
            throw new ErrorDataException("商家有误");
        }
        MerchantShopVO result = new MerchantShopVO(merchant);
        List<ShopVO> shopList = shopService.findEnableList(merchantId).stream()
                .map(ShopVO::new)
                .collect(Collectors.toList());
        result.setShopList(shopList);
        return result;
    }

    /**
     * 查询租户默认店铺
     * (目前在商品导入时使用)
     *
     * @return 失败为null
     */
    @Override
    public ShopExtDTO fetchDefaultShop() {
        // 平台商家
        Merchant merchant = merchantService.fetchPlatformMerchant();
        if (null == merchant) {
            return null;
        }
        // 查询平台商家 启用店铺 默认采购配送店铺在前
        List<Shop> shopList = shopService.findEnableList(merchant.getId());
        if (shopList.isEmpty()) {
            return null;
        }
        ShopExtDTO shopExt = new ShopExtDTO(shopList.get(0));
        shopExt.setMerchantName(merchant.getMerchantName());
        return shopExt;
    }


    /**
     * 删除店铺，有对应商品时不可删除
     *
     * @param id
     * @return
     */
    @Override
    @Caching(evict = {
            @CacheEvict(value = ScmCacheNameConstant.MANAGE_MERCHANT_SHOP, allEntries = true),
            @CacheEvict(value = ScmCacheNameConstant.MANAGE_PRICING_PM_ID, allEntries = true)
    })
    public boolean deleteShop(String id) {
        Shop shop = shopService.getById(id);
        if (null == shop) {
            throw new ErrorDataException("店铺有误");
        }
        int goodsNum = scmManageUtils.countGoodsNum(id);
        if (goodsNum > 0) {
            throw new ErrorDataException("店铺下有商品存在, 不可删除");
        }
        return shopService.removeById(id);
    }


    /**
     * 新增店铺
     *
     * @param req
     * @return
     */
    @Override
    @CacheEvict(value = ScmCacheNameConstant.MANAGE_MERCHANT_SHOP, key = "#req.merchantId")
    public boolean addShop(ShopEditReq req) {
        Shop shop = req.transTo();
        Merchant merchant = merchantService.getById(shop.getMerchantId());
        if (merchant == null) {
            throw new ErrorDataException("店铺商家有误");
        }
        // 图片组保存
        saveShopPhoto(shop, req, shop);
        return shopService.save(shop);
    }

    /**
     * 修改店铺
     *
     * @param req
     * @return
     */
    @Override
    @Caching(evict = {
            @CacheEvict(value = ScmCacheNameConstant.MANAGE_MERCHANT_SHOP, allEntries = true),
            @CacheEvict(value = ScmCacheNameConstant.MANAGE_PRICING_PM_ID, allEntries = true)
    })
    public boolean modifyShop(ShopEditReq req) {
        Shop shop = req.transTo();
        Shop exist = shopService.getById(req.getShopId());
        if (null == exist) {
            throw new ErrorDataException("店铺有误");
        }
        if (StrUtil.isNotEmpty(shop.getMerchantId()) && !StrUtil.equals(shop.getMerchantId(), exist.getMerchantId())) {
            Merchant merchant = merchantService.getById(shop.getMerchantId());
            if (null == merchant) {
                throw new ErrorDataException("店铺商家有误");
            }
            // 店铺商家修改时 同时修改其他关联商家的信息
            modifyMerchantRelation(shop.getId(), exist.getMerchantId(), shop.getMerchantId());
        } else {
            shop.setMerchantId(exist.getMerchantId());
        }
        // 图片组保存
        saveShopPhoto(shop, req, exist);
        return shopService.updateById(shop);
    }

    /**
     * 店铺商家修改时 同时修改其他关联商家的信息
     *
     * @param shopId
     * @param sourceMerchantId 原商家id
     * @param targetMerchantId 修改后商家id
     */
    private void modifyMerchantRelation(String shopId, String sourceMerchantId, String targetMerchantId) {
        // 商品相关
        ScmGlobalThreadPool.getExecutor()
                .execute(() -> goodsCoreService.modifyMerchantByShopBatch(shopId, sourceMerchantId, targetMerchantId));
    }

    /**
     * 设置店铺图片组 (可清空图片列表)
     *
     * @param shop      必须 merchantId
     * @param req       图片列表
     * @param existShop 已有图片组编号
     */
    private void saveShopPhoto(Shop shop, ShopEditReq req, Shop existShop) {
        PhotoGroupDTO photoGroupDTO = new PhotoGroupDTO();
        photoGroupDTO.setMerchantId(shop.getMerchantId());
        photoGroupDTO.setCategoryTag(PhotoTypeEnum.ShopPhotos.getDesc());
        // 轮播图
        if (null != req.getPhotoList()) {
            photoGroupDTO.setGroupNum(existShop.getPhotoGroupNum());
            photoGroupDTO.setGroupName("店铺轮播图");
            photoGroupDTO.transPhotoList(req.getPhotoList());
            shop.setPhotoGroupNum(editGroupNum(photoGroupDTO));
        }
        // 店铺收款码
        if (null != req.getPayCodeList()) {
            photoGroupDTO.setGroupNum(existShop.getPayCode());
            photoGroupDTO.setGroupName("店铺收款码");
            photoGroupDTO.transPhotoList(req.getPayCodeList());
            shop.setPayCode(editGroupNum(photoGroupDTO));
        }
        // 店铺二维码
        if (null != req.getQrcodeList()) {
            photoGroupDTO.setGroupNum(existShop.getQrcode());
            photoGroupDTO.setGroupName("店铺二维码");
            photoGroupDTO.transPhotoList(req.getQrcodeList());
            shop.setQrcode(editGroupNum(photoGroupDTO));
        }
        // 店铺Logo
        if (null != req.getShopLogoList()) {
            photoGroupDTO.setGroupNum(existShop.getShopLogo());
            photoGroupDTO.setGroupName("店铺Logo");
            photoGroupDTO.transPhotoList(req.getShopLogoList());
            shop.setShopLogo(editGroupNum(photoGroupDTO));
        }
    }

    private String editGroupNum(PhotoGroupDTO photoGroupDTO) {
        PhotoGroupManage photoGroupManage = photoManageCoreService.editPhotoGroup(photoGroupDTO);
        return (null == photoGroupManage) ? null : photoGroupManage.getGroupNum();
    }
}
